'use strict';

angular.module('cmsysApp')
  .controller(
    'userInfoCtrl',
    ['$scope', '$http', '$state', '$stateParams', 'baseService',
      function ($scope, $http, $state, $stateParams, baseService) {
        $scope.user1 = {};
        $scope.pwdUser = {};
        $scope.hide1 = $scope.hide2 = true;
        baseService.query({url: baseUrl + "/company/findAll"}).then(function (data) {
          $scope.companies = data.companies;
        });
        baseService.query({url: baseUrl + '/user/curUser'}).then(function (data) {
          data.user.cid += "";
          $scope.user = data.user;
          $scope.user1 = data.user;
        });
        $scope.updateUser = function () {
          baseService.edit({url: baseUrl + '/user/updateUser', params: $scope.user1});
        };
        $scope.editPwd = function () {
          $scope.pwdUser.password = $scope.pwdUser.password1;
          baseService.edit({url: baseUrl + '/user/updateUser', params: $scope.pwdUser});
        };
        $scope.ajaxCheck = function (username) {
          $scope.pwdUser.id = $scope.user.id;
          $scope.pwdUser.username = $scope.user.username;
          return baseService.query({
            url: baseUrl + '/user/check',
            params: username ? {username: $scope.user.username} : $scope.pwdUser
          });
        };
      }])
  .directive('sameTo', [function () {
    return {
      require: '^?form',
      link: function (scope, elem, attrs, ctrl) {
        ctrl.password2.$parsers.push(function (viewValue) {
            ctrl.password2.$setValidity('inconsistent', viewValue === $('#' + attrs.sameTo).val());
            return viewValue;
          }
        );
      }
// elem.keydown(function () {
//   scope.form2.password2.$setValidity('inconsistent', elem.val() === $('#' + attrs.sameTo).val());
// });
    }
  }])
  .directive('ajaxCheck', [function () {
    return {
      require: '^?form',
      link: function (scope, elem, attrs, ctrl) {
        elem.bind('blur', function () {
          scope.ajaxCheck(attrs.ajaxCheck).then(function (data) {
            scope.form1.username.$setValidity('invalid', data.valid);
            scope.form2.password.$setValidity('invalid', !data.valid);
          });
        });
      }
    }
  }]);
;
